﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

namespace Infrastructure.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class AttributeExtensions
    {
        /// <summary>
        /// 获取枚举的描述
        /// </summary>
        /// <param name="en">枚举</param>
        /// <returns>返回枚举的描述</returns>
        public static string GetEnumDescription(this Enum en)
        {
            Type type = en.GetType();   //获取类型
            MemberInfo[] memberInfos = type.GetMember(en.ToString());   //获取成员
            if (memberInfos.Length > 0)
            {
                if (memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false) is DescriptionAttribute[] attrs && attrs.Length > 0)
                {
                    return attrs[0].Description;    //返回当前描述
                }
            }
            return en.ToString();
        }

        /// <summary>
        /// 获取枚举的描述的字典
        /// </summary>
        /// <returns></returns>
        public static IDictionary<T, string> GetEnumDescriptionCollection<T>()
            where T : Enum
        {
            IDictionary<T, string> output = new Dictionary<T, string>();

            foreach (T item in Enum.GetValues(typeof(T)))
            {
                output.Add(item, GetEnumDescription(item));
            }
            return output;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IList<KeyValuePair<T, string>> GetEnumDescriptionKeyPairList<T>()
            where T : Enum
        {
            IList<KeyValuePair<T, string>> output = new List<KeyValuePair<T, string>>();

            foreach (T item in Enum.GetValues(typeof(T)))
            {
                output.Add(new KeyValuePair<T, string>(item, GetEnumDescription(item)));
            }
            return output;
        }

    }
}
